<?php

namespace slinks\extensions\action\core;

use slinks\core\HttpFoundation\IRequest;
use slinks\extensions\action\exception\FlattenException;
use slinks\extensions\action\exception\HttpExceptionInterface;
use slinks\core\Templating\EngineInterface;
use slinks\core\HttpFoundation\Response;

/**
 * Description of DelegatingFrontController
 *
 * @author navid
 */
class DelegatingFrontController implements IFrontController {

    private $controllers = array();
    private $engine;
    private $debug;
    
    function __construct(EngineInterface $engine,$debug){
        $this->engine = $engine;
        $this->debug = $debug;
    }
    
    public function handle(IRequest $request) {
        $response = null;
        try{
            foreach($this->controllers as $controller) {
                $response = $controller->handle($request);
                if ($response != null) {
                    //$request->getSession()->save();
                    break;
                }
            }
        }catch(\Exception $e){
            // TODO: move this logic into its own controller.
            // it makes sense that these controllers implement the interceptor pattern as well.
            // however it is strange to do that here and with actions maybe we just need to have pre route interceptors. 
            // and actually have the interceptors do routing as well 
            
            $flattenException = FlattenException::create($e);
            if ($e instanceof HttpExceptionInterface) {
                $flattenException->setStatusCode($e->getStatusCode());
                $flattenException->setHeaders($e->getHeaders());
            }
            
            $name = $this->debug ? 'exception' : 'error';
            $format = $request->getRequestFormat();
            //TODO: we dont want to use the full template since right now we are using with joomla.
            //if ($this->debug && 'html' == $format) {
           //     $name = 'exception_full';
           // }
            $template = $name.'.'.$format.'.twig';

            // TODO: make sure template exisits for format. 

            $code = $flattenException->getStatusCode();
            $response = new Response();
            $response->setContent($this->engine->render($template,
                                  array(
                                    'status_code'    => $code,
                                    'status_text'    => Response::$statusTexts[$code],
                                    'exception'      => $flattenException,
                                    'currentContent' => $request->getContent(),
            )));
            
            $response->setStatusCode($code);
            $response->headers->replace($flattenException->getHeaders());
        }
        
        return $response;
    }

    public function addFrontController(IFrontController $controller) {
        $this->controllers[] = $controller;
    }

}
